package com.ruoyi.web.controller.teaching;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.teaching.domain.VettingRequest;
import com.ruoyi.teaching.domain.vo.PlatformCCourseOutlineNodeVO;
import com.ruoyi.teaching.domain.vo.PlatformCCourseVO;
import com.ruoyi.teaching.service.PlatformCCourseService;
import com.ruoyi.teaching.utils.UniversalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 王旭
 * @since 2024-06-13
 */
@RestController
@RequestMapping("/platform/course")
@Api(tags = "platform-备课授课管理")
@Validated
public class PlatformCCourseController {
    @Autowired
    private PlatformCCourseService platformCCourseService;

    /**
     * 老师查询自己的备课授课列表
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:list')")
    @GetMapping("/list")
    @ApiOperation(value = "老师查询自己的备课授课列表", notes = "老师查询自己的备课授课列表")
    public AjaxResult list( Integer professionalCategoryId, Integer professionalId, Integer courseVisible) {
        return platformCCourseService.selectPlatformCCourseList(professionalCategoryId, professionalId, courseVisible);
    }

    /**
     * 老师查询已通过的备课授课
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:listPassed')")
    @GetMapping("/listPassed")
    @ApiOperation(value = "老师查询已通过的备课授课", notes = "老师查询已通过的备课授课")
    public AjaxResult listPassed(Integer finishCourse) {
        return platformCCourseService.listPassed(finishCourse);
    }

    /**
     * 前台用户查询已通过的备课授课列表
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:list')")
    @GetMapping("/listUser")
    @ApiOperation(value = "前台用户查询已通过的备课授课列表", notes = "用户查询已通过的备课授课列表")
    public AjaxResult listUser(Integer pageNum, Integer pageSize, Integer professionalCategoryId, Integer professionalId, Integer courseVisible, Integer sortord, String courseName, Integer courseStatus) {
        return platformCCourseService.selectPlatformCCourseListUser(pageNum,pageSize,professionalCategoryId, professionalId, courseVisible,sortord,courseName,courseStatus);
    }

    /**
     * 系统管理员查询备课授课列表
     */
    // @PreAuthorize("@ss.hasPermi('platform:course:listSystemAdmin')")
    @GetMapping("/listSystemAdmin")
    @ApiOperation(value = "系统管理员查询备课授课列表", notes = "系统管理员查询备课授课列表")
    public AjaxResult listSystemAdmin(Integer pageNum, Integer pageSize, String courseName, String createBy, Integer professionalCategoryId,Integer vettingStatus) {
        return platformCCourseService.selectPlatformCCourseListSystemAdmin(pageNum,pageSize,courseName, createBy, professionalCategoryId,vettingStatus);
    }

    /**
     * 学校管理员查询备课授课列表
     */
    // @PreAuthorize("@ss.hasPermi('platform:course:listSchoolAdmin')")
    @GetMapping("/listSchoolAdmin")
    @ApiOperation(value = "学校管理员查询备课授课列表", notes = "学校管理员查询备课授课列表")
    public AjaxResult listSchoolAdmin(Integer pageNum, Integer pageSize, String courseName, String createBy, Integer professionalCategoryId,Integer vettingStatus) {
        return platformCCourseService.listSchoolAdmin(pageNum,pageSize,courseName, createBy, professionalCategoryId,vettingStatus);
    }

    /**
     * 学生查询备课授课列表（根据班级查）
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:listStudent')")
    @GetMapping("/listStudent")
    @ApiOperation(value = "学生查询备课授课列表（根据班级查）", notes = "学生查询备课授课列表（根据班级查）")
    public AjaxResult listStudent() {
        return platformCCourseService.selectPlatformCCourseListStudent();
    }

    /**
     * 学生查询备课授课列表（作业管理，只能查到已有作业的课程）
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:listStudentTask')")
    @GetMapping("/listStudentTask")
    @ApiOperation(value = "学生查询备课授课列表（作业管理）", notes = "学生查询备课授课列表（作业管理）")
    public AjaxResult listStudentTask() {
        return platformCCourseService.selectPlatformCCourseListStudentTask();
    }

    /**
     * 获取在线课程的前五个热搜
     */
    @GetMapping("/hotSearch")
    @ApiOperation(value = "获取在线课程的前五个热搜", notes = "获取在线课程的前五个热搜")
    public AjaxResult hotSearch() {
        return platformCCourseService.selectHotSearch();
    }

    /**
     * 获取老师信息
     */
    @GetMapping("/teacherInfo")
    @ApiOperation(value = "获取老师信息", notes = "获取老师信息")
    public AjaxResult teacherInfo(Integer userId) {
        return platformCCourseService.selectTeacherInfo(userId);
    }

    /**
     * 增加课程浏览量
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:listStudentTask')")
    @PostMapping("/addCourseView")
    @ApiOperation(value = "增加课程浏览量", notes = "增加课程浏览量")
    public void addCourseView(@RequestParam Integer courseId) {
        platformCCourseService.addCourseView(courseId);
    }

//    /**
//     * 增加课程学习人数
//     */
////    @PreAuthorize("@ss.hasPermi('platform:course:listStudentTask')")
//    @PostMapping("/addCourseStudent")
//    @ApiOperation(value = "增加课程学习人数", notes = "增加课程学习人数")
//    public void addCourseStudent(@RequestParam Integer courseId) {
//        platformCCourseService.addCourseStudent(courseId);
//    }

    /**
     * 查询备课授课列表详细信息
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "查询备课授课列表详细信息", notes = "查询备课授课列表详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return platformCCourseService.selectPlatformCCourseById(id);
    }

    /**
     * 新增备课授课
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:add')")
    @Log(title = "【新增备课授课】", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增备课授课", notes = "新增备课授课")
    @PostMapping
    public AjaxResult add(@RequestBody PlatformCCourseVO platformCCourseVO) {

        List<String> errorMessages = validateErrorMessages(platformCCourseVO);
        if (!CollectionUtils.isEmpty(errorMessages)) {
            return AjaxResult.error(String.join(", ", errorMessages));
        }

        return platformCCourseService.insertPlatformCCourse(platformCCourseVO);
    }


    /**
     * 修改备课授课
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:edit')")
    @Log(title = "【修改备课授课】", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改备课授课", notes = "修改备课授课")
    public AjaxResult edit(@RequestBody PlatformCCourseVO platformCCourseVO) {

        List<String> errorMessages = validateErrorMessages(platformCCourseVO);
        if (!CollectionUtils.isEmpty(errorMessages)) {
            return AjaxResult.error(String.join(", ", errorMessages));
        }

        return platformCCourseService.updatePlatformCCourse(platformCCourseVO);
    }

    /**
     * 审核备课授课
     */
    @Log(title = "【审核备课授课】", businessType = BusinessType.UPDATE)
//    @PreAuthorize("@ss.hasPermi('platform:course:vetting')")
    @PutMapping("/vetting")
    @ApiOperation(value = "审核备课授课", notes = "审核备课授课")
    public AjaxResult vetting(@Valid @RequestBody VettingRequest vettingRequest) {
        if(vettingRequest.getVettingStatus() == 2 && null == vettingRequest.getNotPassingType()){
            return AjaxResult.error("请选择不通过的理由");
        }
        return platformCCourseService.updatePlatformCCourseVetting(vettingRequest);
    }

    /**
     * 删除备课授课
     */
//    @PreAuthorize("@ss.hasPermi('platform:course:remove')")
    @Log(title = "【删除备课授课】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除备课授课", notes = "删除备课授课")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return platformCCourseService.deletePlatformCCourseByIds(ids);
    }

    /**
     * 记录用户学习的课程和课时
     *
     * @param courseId 课程ID
     * @param sectionId 课时ID
     * @return 操作结果
     */
    @PostMapping("/recordLearning")
    @ApiOperation(value = "记录用户学习的课程和课时", notes = "记录用户学习的课程和课时")
    @Log(title = "【记录用户学习的课程和课时】", businessType = BusinessType.INSERT)
    public AjaxResult recordLearning(@RequestParam Long courseId, @RequestParam Long sectionId, @RequestParam(value = "fileUrl", required = false) String fileUrl) {
        return platformCCourseService.recordLearning(courseId, sectionId, fileUrl);
    }

    /**
     * 删除正在学习的人员记录
     */
    @PostMapping("/deleteLearningRecord")
    @ApiOperation(value = "删除正在学习的人员记录", notes = "删除正在学习的人员记录")
    @Log(title = "【删除正在学习的人员记录】", businessType = BusinessType.DELETE)
    public void deleteLearningRecord() {
        platformCCourseService.deleteLearningRecord();
    }


    private List<String> validateErrorMessages(PlatformCCourseVO platformCCourseVO) {
        List<String> errorMessages = new ArrayList<>();
        errorMessages.addAll(UniversalUtil.validate(platformCCourseVO.getCourseName(), 1, 20, true, "课程名称"));
        errorMessages.addAll(UniversalUtil.validate(platformCCourseVO.getTeacherName(), 1, 20, false, "授课老师"));
        errorMessages.addAll(UniversalUtil.validate(platformCCourseVO.getCourseIntroduce(), 1, 500, false, "课程介绍"));
        if (platformCCourseVO.getCourseType() == 0) {
            List<PlatformCCourseOutlineNodeVO> outline = platformCCourseVO.getOutline();
            if (!CollectionUtils.isEmpty(outline)) {
                for (PlatformCCourseOutlineNodeVO platformCCourseOutlineNodeVO : outline) {
                    if (platformCCourseOutlineNodeVO.getParentId() == 0) {
                        errorMessages.addAll(UniversalUtil.validate(platformCCourseOutlineNodeVO.getName(), 1, 20, true, "章节名称：【" + platformCCourseOutlineNodeVO.getName() + "】"));
                    } else {
                        errorMessages.addAll(UniversalUtil.validate(platformCCourseOutlineNodeVO.getName(), 1, 20, true, "课时名称：【" + platformCCourseOutlineNodeVO.getName() + "】"));
                    }
                }
            } else {
                errorMessages.add("请添加课程大纲");
            }
        } else {
            errorMessages.addAll(UniversalUtil.validateNotEmpty(platformCCourseVO.getCourseUrl(), "课程外部链接"));
        }
        return errorMessages;
    }
}

